package cn.rengy.web.framework.wxmp;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rengy.tool.core.util.ExceptionPrintUtils;
import cn.rengy.tpa.wxmp.param.SignatureParam;
import cn.rengy.tpa.wxmp.param.WechatParamName;
import cn.rengy.web.framework.support.DataConverterImpl;

@Controller
@RequestMapping(value = "/wxportal")
public class WechatController {
	private static Logger logger = LoggerFactory.getLogger(WechatController.class);
	@Autowired
	private WechatService wechatService;
	@Autowired
	private WxAppService wxAppService; 
	@Autowired
	private DataConverterImpl dataConverterImpl;
	/**
	 * 微信服务处理入口
	 * @param appid 公众号appid
	 * @param companyid 企业id
	 * @param request
	 * @return
	 */
	@RequestMapping()
	@ResponseBody
	public String access(@RequestParam("appid") String appid,
			@RequestParam(required=false,name="a") Long company_id,
			HttpServletRequest request){
		WxApp wxApp=wxAppService.getApp(appid);
		
		String signature = request.getParameter(WechatParamName.SIGNATURE);
		String timestamp = request.getParameter(WechatParamName.TIMESTAMP);
		String nonce = request.getParameter(WechatParamName.NONCE);
		String echostr = request.getParameter(WechatParamName.ECHOSTR);
		SignatureParam signatureParam =new SignatureParam();
		signatureParam.setEchostr(echostr);
		signatureParam.setNonce(nonce);
		signatureParam.setSignature(signature);
		signatureParam.setTimestamp(timestamp);
		
		String result="success";
		try {
			result =wechatService.execute(appid, company_id, wxApp.getToken(), signatureParam, request.getInputStream());
			logger.debug("response text:{}",result);
		} catch (Exception e) {
			logger.error(ExceptionPrintUtils.getTrace(e));
		}
		return result;
	}
}
